<template>
  <div class="page">

    <el-form ref="addForm" class="add_hospital_form" :model="addForm" :rules="addFormRules" label-width="140px" :disabled="status == 3">
      <div class="title">基础信息</div>
      <div class="base_info">
        <el-form-item label="医院名称：" prop="name">
          <el-input v-model="addForm.name" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="所在城市：" prop="city">
          <el-select v-model="addForm.city" filterable class="a_select">
            <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="医院地址：" prop="address">
          <el-input v-model="addForm.address" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="擅长项目：">
          <el-select v-model="addForm.expertProject" multiple class="a_select">
            <el-option v-for="(item,index) in projectList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="经营时间：">
          <el-input v-model="addForm.businessTime" />
        </el-form-item>
        <el-form-item label="成立时间：">
          <el-input v-model="addForm.establishDate" />
        </el-form-item>
        <el-form-item label="前台电话：" prop="receptionTel">
          <el-input v-model="addForm.receptionTel" />
        </el-form-item>
        <el-form-item label="门诊面积：">
          <el-input v-model="addForm.outpatientArea" />
        </el-form-item>
        <el-form-item label="诊室数量：">
          <el-input v-model="addForm.outpatientRootCnt" />
        </el-form-item>
        <el-form-item label="牙椅数量：">
          <el-input v-model="addForm.toothChairCnt" />
        </el-form-item>
        <el-form-item label="医保政策：">
          <el-radio-group v-model="addForm.medicalInsurancePolicy">
            <el-radio :label="1">支持医保</el-radio>
            <el-radio :label="0">不支持医保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item />
        <el-form-item label="营业执照：">
          <el-upload :action="COMMONFILEUPLOAD" list-type="picture-card" :limit="1" :file-list="addForm.businessLicense" :headers="uploadHeaders" :on-success="(response, file, fileList) =>
              onSuccess(response, file, fileList, 'businessLicense')" :on-remove="(file,fileList) => onRemove(file,fileList,'businessLicense')" :on-preview="previewImage">
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
        <el-form-item label="执业许可证：">
          <el-upload :action="COMMONFILEUPLOAD" list-type="picture-card" :limit="1" :file-list="addForm.practiceLicense" :headers="uploadHeaders" :on-success="(response, file, fileList) =>
              onSuccess(response, file, fileList, 'practiceLicense')" :on-remove="(file,fileList) => onRemove(file,fileList,'practiceLicense')" :on-preview="previewImage">
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </div>

      <div class="title">环境介绍</div>
      <el-form-item label="环境图片：">
        <el-upload :action="COMMONFILEUPLOAD" list-type="picture-card" :limit="12" :file-list="addForm.surroundingsPic" :headers="uploadHeaders" :on-success="(response, file, fileList) =>
            onSuccess(response, file, fileList, 'surroundingsPic')" :on-remove="(file,fileList) => onRemove(file,fileList,'surroundingsPic')" :on-preview="previewImage">
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="交通指引：">
        <wang-editor :key="randomKey" :value="addForm.trafficGuide" @change="(res) => editorChange(res, 'trafficGuide')" />
      </el-form-item>

      <el-form-item label="停车指引：">
        <wang-editor :key="randomKey" :value="addForm.parkGuide" @change="(res) => editorChange(res, 'parkGuide')" />
      </el-form-item>

      <el-form-item label="门诊介绍：">
        <wang-editor :key="randomKey" :value="addForm.outpatientIntroduce" @change="(res) => editorChange(res, 'outpatientIntroduce')" />
      </el-form-item>

      <div class="title">预约信息</div>
      <el-form-item label="是否开放预约：">
        <el-radio-group v-model="addForm.isOpened">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="负责人：" prop="principal">
        <user-select v-model="addForm.principal" :multiple="false"></user-select>
      </el-form-item>

      <el-form-item label="预约注意事项：">
        <wang-editor :key="randomKey" placeholder="周六不可以安排预约，预约前需要注意跟门诊确认，每天最多可预约5个，主推医生，医保使用说明等" :value="addForm.attention" @change="(res) => editorChange(res, 'attention')" />
      </el-form-item>

      <el-form-item label="活动价格政策：">
        <wang-editor :key="randomKey" placeholder="周六不可以安排预约，预约前需要注意跟门诊确认，每天最多可预约5个" :value="addForm.activityPricingStrategy" @change="(res) => editorChange(res, 'activityPricingStrategy')" />
      </el-form-item>

      <el-form-item label="预约紧急联系人：">
        <!-- <wang-editor placeholder="" @change="(res) => editorChange(res, 'detailedIntroduction')" :value="addForm.detailedIntroduction" :key="randomKey"></wang-editor> -->
        <el-input v-model="addForm.emergencyContact" type="textarea" placeholder="周六不可以安排预约，预约前需要注意跟门诊确认，每天最多可预约5个" :rows="areaRows" :resize="areaResize" />
      </el-form-item>

      <el-form-item label="短信交通说明：" prop="smsContentConfig">
        <!-- <wang-editor placeholder="请将下方红色部分内容填入，黑色内容为自动生成，请不要填写！" @change="(res) => editorChange(res, 'detailedIntroduction')" :value="addForm.detailedIntroduction" :key="randomKey"></wang-editor> -->
        <el-input v-model="addForm.smsContentConfig" type="textarea" maxlength="20" show-word-limit placeholder="请输入短信交通说明" :rows="areaRows" :resize="areaResize" />
        <!-- <div class="show_tips">
          <span class="name">短信模板：</span>
          <div class="txt">【邦正口腔】恭喜您预约成功，预约人：周世，预约时间：2021-10-24 19:00，预约医院：欧卡多口腔，<span class="cred">地址电话：南山区大冲国际中心25层AF室（0755-33372595）交通说明：高新园地铁站B出口50米（平安银行楼上），请按照预约时间准时前往就诊，如有问题可联系我们工作人员。</span></div>
        </div> -->
      </el-form-item>

      <el-form-item label="门诊价目表：">
        <el-upload :action="COMMONFILEUPLOAD" list-type="picture-card" :limit="6" :file-list="addForm.outpatientPriceList" :headers="uploadHeaders" :on-success="(response, file, fileList) =>
            onSuccess(response, file, fileList, 'outpatientPriceList')" :on-remove="(file,fileList) => onRemove(file,fileList,'outpatientPriceList')" :on-preview="previewImage">
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="排序：" prop="orderNum">
        <!-- <el-input v-model.number="addForm.orderNum" style="width:240px;" /> -->
        <el-input-number v-model="addForm.orderNum" class="el_input_number" :controls="false"></el-input-number>
      </el-form-item>

      <el-form-item label="">
        <el-button type="primary" :loading="loading" @click="saveInfo">保 存</el-button>
        <el-button type="default" :disabled="false" @click="goBack()">取 消</el-button>
      </el-form-item>

    </el-form>

    <!-- 图片预览 开始 -->
    <el-dialog custom-class="preview_dialog" :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- 图片预览 开始 -->

  </div>
</template>
<script>
import WangEditor from "@/components/wangEditor";
import {
  COMMONFILEUPLOAD,
  GETPROJECTOPTIONS,
  GETCITYOPTIONS,
} from "@/http/system";
import {
  ADDHOSPITALINFO,
  GETHOSPITALINFO,
  BASEURL,
  EDITHOSPITALINFO,
} from "@/http/hospital";
import { deepClone, showToast } from "@/common/util";
import UserSelect from "@/components/select/user";
export default {
  components: {
    WangEditor,
    UserSelect,
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: "",
      status: "",
      addForm: { medicalInsurancePolicy: 1, isOpened: 1 },
      randomKey: "",
      areaRows: 5,
      areaResize: "none",
      COMMONFILEUPLOAD: COMMONFILEUPLOAD,
      uploadHeaders: {},
      addFormRules: {
        name: [{ required: true, message: "请输入医院名称", trigger: "blur" }],
        city: [{ required: true, message: "请选择城市", trigger: "blur" }],
        address: [
          { required: true, message: "请输入所在地址", trigger: "blur" },
        ],
        receptionTel: [
          { required: true, message: "请输入前台电话", trigger: "blur" },
        ],
        smsContentConfig: [
          { required: true, message: "请输入短信交通说明", trigger: "blur" },
        ],
        orderNum: [{ required: true, message: "请输入排序", trigger: "blur" }],
        principal: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
      },
      projectList: [],
      cityList: [],
      loading: false,
    };
  },
  created() {
    const token = sessionStorage.getItem("token");
    this.uploadHeaders = { Authorization: token };
  },
  mounted() {
    const o = this.$route.query;

    /**
     * 新增：status：1
     * 编辑：status：2
     * 详情：status：3
     */

    this.status = o.status;
    if (o.id) {
      // let txt = '编辑医院'
      // if(o.status == 3){
      //   txt = '医院详情'
      // }
      // document.getElementById("lastBreadcrumb").innerText = txt;
      this.getInfo(this.$route.query.id);
    }

    this.getProject();
    this.getCity();
  },
  methods: {
    // 监听富文本输入
    editorChange(e, id) {
      this.$set(this.addForm, id, e);
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || [];
      });
    },

    // 获取所有城市
    getCity() {
      GETCITYOPTIONS().then((res) => {
        this.cityList = res.data || [];
      });
    },

    // 新增医院
    saveInfo() {
      const _this = this;
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        const oParams = deepClone(_this.addForm);
        oParams.id = _this.$route.query.id;

        if (oParams.expertProject) {
          oParams.expertProject = oParams.expertProject.toString();
        }

        if (oParams.city) {
          const o = _this.cityList.find((k) => k.code == oParams.city);
          oParams.cityName = o ? o.name : "";
        }

        // 营业执照
        if (oParams.businessLicense && oParams.businessLicense.length > 0) {
          oParams.businessLicense = oParams.businessLicense[0].path;
        } else {
          oParams.businessLicense = "";
        }

        // 执业许可
        if (oParams.practiceLicense && oParams.practiceLicense.length > 0) {
          oParams.practiceLicense = oParams.practiceLicense[0].path;
        } else {
          oParams.practiceLicense = "";
        }

        // 价目表
        if (
          oParams.outpatientPriceList &&
          oParams.outpatientPriceList.length > 0
        ) {
          const m = [];
          oParams.outpatientPriceList.map((k) => {
            m.push(k.path);
          });
          oParams.outpatientPriceList = m.toString();
        } else {
          oParams.outpatientPriceList = "";
        }

        // 环境图片
        if (oParams.surroundingsPic && oParams.surroundingsPic.length > 0) {
          const m = [];
          oParams.surroundingsPic.map((k) => {
            m.push(k.path);
          });
          oParams.surroundingsPic = m.toString();
        } else {
          oParams.surroundingsPic = "";
        }

        delete oParams.expertProjectNames;

        _this.loading = true;

        // 编辑医院
        if (oParams.id) {
          EDITHOSPITALINFO(oParams).then((res) => {
            _this.loading = false;
            if (res.code == 200) {
              showToast({
                message: "编辑成功",
                type: "success",
              });
              _this.goBack();
            }
          });
          return false;
        }

        console.log(oParams);
        ADDHOSPITALINFO(oParams).then((res) => {
          _this.loading = false;
          if (res.code == 200) {
            showToast({
              message: "新增成功",
              type: "success",
            });
            _this.goBack();
          }
        });
      });
    },

    /** 监听文件上传成功 */
    onSuccess(response, file, fileList, id) {
      console.log(response);
      if (response.code == 200) {
        const obj = this.addForm[id] || [];
        const n = {};
        n.name = response.data;
        n.url = BASEURL + response.data;
        n.path = response.data;
        obj.push(n);
        // this.$set(this.addForm, id, response.data);
        this.$set(this.addForm, id, obj);
      }
    },

    // 获取医院详情
    getInfo(id) {
      GETHOSPITALINFO({ id: id }).then((res) => {
        const o = res.data || {};
        const obj = Object.assign(
          o.appointment || {},
          o.hospital || {},
          o.surroundings || {}
        );

        // 设置擅长项目
        if (obj.expertProject) {
          const arr = [];
          obj.expertProject.split(",").map((k) => {
            arr.push(Number(k));
          });

          obj.expertProject = arr;
        }

        // 设置营业执照
        if (obj.businessLicense) {
          obj.businessLicense = [
            {
              name: obj.businessLicense,
              url: BASEURL + obj.businessLicense,
              path: obj.businessLicense,
            },
          ];
        } else {
          obj.businessLicense = [];
        }

        // 设置职业许可证
        if (obj.practiceLicense) {
          obj.practiceLicense = [
            {
              name: obj.practiceLicense,
              url: BASEURL + obj.practiceLicense,
              path: obj.practiceLicense,
            },
          ];
        } else {
          obj.practiceLicense = [];
        }

        // 设置环境图片
        if (obj.surroundingsPic) {
          const arr = [];
          obj.surroundingsPic.split(",").map((k) => {
            const o = {
              name: k,
              url: BASEURL + k,
              path: k,
            };
            arr.push(o);
          });
          obj.surroundingsPic = arr;
        } else {
          obj.surroundingsPic = [];
        }

        // 设置门诊价目表
        if (obj.outpatientPriceList) {
          const arr = [];
          obj.outpatientPriceList.split(",").map((k) => {
            const o = {
              name: k,
              url: BASEURL + k,
              path: k,
            };
            arr.push(o);
          });
          obj.outpatientPriceList = arr;
        } else {
          obj.outpatientPriceList = [];
        }

        delete obj.hospitalId;
        this.addForm = { ...obj };
        console.log(this.addForm);
        this.randomKey = Math.random();
      });
    },

    /** 删除文件 */
    onRemove(file, fileList, id) {
      console.log(fileList);
      this.$set(this.addForm, id, fileList);
    },

    // 返回
    goBack() {
      this.$router.go(-1);
    },

    // 预览图片
    previewImage(e) {
      console.log(e);
      this.dialogVisible = true;
      this.dialogImageUrl = e.url;
    },
  },
};
</script>
<style lang="scss">
.add_hospital_form {
  .a_select {
    width: 100%;
  }
}

.el-dialog__wrapper {
  z-index: 99999 !important;
}
.v-modal {
  z-index: 99998 !important;
}
.el_input_number {
  .el-input__inner {
    text-align: left;
  }
}
.el-select-dropdown {
  z-index: 99999 !important;
}
</style>
<style lang="scss" scoped>
.page {
  background: #fff;
  border-radius: 6px;
  padding: 0 16px;
  overflow: hidden;
}
.title {
  font-size: 20px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: bold;
  color: #000000;
  margin: 24px 0;
}
.base_info {
  display: flex;
  flex-wrap: wrap;
  .el-form-item {
    flex: 0 0 50%;
  }
}
.show_tips {
  display: flex;
  line-height: 1.8;
  margin: 10px 0;
  .name {
    flex-shrink: 0;
  }
  .txt {
    flex: 1;
    .cred {
      color: #f00;
    }
  }
}
</style>
